package org.hackystat.devcathlon.ui.page.form.validators;

import java.util.Map;

import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.validator.AbstractValidator;
import org.hackystat.devcathlon.engine.match.Match;
import org.hackystat.devcathlon.engine.team.TeamManager;

/**
 * Match name validator.
 * 
 * @author Anthony Du
 */
public class MatchNameValidator extends AbstractValidator {

  /** Support Serialization. */
  private static final long serialVersionUID = 1L;
  /** The match. */
  private Match match;

  /**
   * Match name validator constructor.
   */
  public MatchNameValidator() {
    // empty constructor.
  }
  
  /**
   * Match name validator constructor.
   * 
   * @param user The current match.
   */
  public MatchNameValidator(Match match) {
    this.match = match;
  }

  /**
   * Validates the given item.
   * 
   * @param validatable
   *          The item to be validated.
   */
  @Override
  protected void onValidate(IValidatable validatable) {
    String value = (String) validatable.getValue();
    if (null != TeamManager.getInstance().getTeam(value)
        && !checkMatchName(value)) {
      error(validatable);
    }
  }
  
  /**
   * Checks to see if current match has the same name.
   * 
   * @param name The match name to compare.
   * @return True if the match has the same name, else false 
   */
  private boolean checkMatchName(String name) {
    // ignore current match's name for validation.
    if (null == match) {
      return false;
    }
    if (name.equals(this.match.getName())) {
      return true;
    }
    return false;
  }

  /**
   * Specifies the resource key for this validation.
   * 
   * @return The resource key.
   */
  @Override
  protected String resourceKey() {
    return "MatchNameValidator";
  }

  /**
   * Validation keys map. This maps the keys associated to the error message.
   * 
   * @param validatable Validatable items.
   * @return The map of keys
   */
  @SuppressWarnings("unchecked")
  @Override
  protected Map variablesMap(IValidatable validatable) {
    Map map = super.variablesMap(validatable);
    return map;
  }
}
